package com.rzx.mybackend.controller.system;

import com.rzx.mybackend.common.Result;
import com.rzx.mybackend.entity.User;
import com.rzx.mybackend.service.LoginService;
import com.rzx.mybackend.service.UserService;
import com.rzx.mybackend.vo.UserVO;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * LoginController
 *
 * @author renzhexian
 * @date 2025/7/15
 */
@RestController
@RequestMapping
@AllArgsConstructor
public class LoginController {

    private static final Logger log = LoggerFactory.getLogger(LoginController.class);

    private final LoginService loginService;

    private final AuthenticationManager authenticationManager;

    private final UserService userService;


    /*
    登录接口
     */
    @PostMapping("/login")
    public Result<UserVO> login(@RequestBody User user) {

        if (user.getUserName() == null || user.getUserName().isEmpty() ||
            user.getPassword() == null || user.getPassword().isEmpty()) {
            throw new RuntimeException("用户名或密码不能为空!");
        }
        try {
            // 封装认证信息（用户名和密码）
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());

            // 触发认证流程 → 会调用 UserDetailsService
            Authentication authentication = authenticationManager.authenticate(authenticationToken);

            // 将认证结果放入安全上下文
            SecurityContextHolder.getContext().setAuthentication(authentication);

            // 生成token
            String token = loginService.generateToken(user.getUserName(),SecurityContextHolder.getContext().getAuthentication().toString());

            return Result.success(UserVO.builder()
                    .userName(user.getUserName())
                    .token(token)
                    .role(userService.getRoleByUserName(user.getUserName()))
                    .build());

        } catch (Exception e) {
            log.error("登录失败: {}", e.getMessage());
            throw new RuntimeException("用户名或密码错误!");
        }
    }

    @DeleteMapping("/userlogout")
    public Result<String> logout() {
        // 清除安全上下文中的认证信息
        SecurityContextHolder.clearContext();
        return Result.success("退出成功!");
    }

}
